package com.lancoo.answer.view.xgPaResultView

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import com.lancoo.answer.databinding.EvXgPaFragmentResultBinding
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.CognitiveBean
import com.lancoo.answer.model.eventBean.ResultChildClickEvent
import com.lancoo.answer.util.*
import com.lancoo.answer.view.base.XBaseFragment
import com.lancoo.answer.view.dialog.XgDialogLevelUp
//import com.lancoo.answer.view.dialog.XgDialogLevelUp
import com.lancoo.answer.view.xgPaResultView.adapter.XgPaResultAnswerSheetParentAdapter
import com.lancoo.answer.widget.CountNumberView
import org.greenrobot.eventbus.EventBus
import java.lang.Math.abs

class XgPaResultFragment() : XBaseFragment<EvXgPaFragmentResultBinding>() {

    companion object {
        private var mIsShowLevelChangeDialog = false
        fun loadFragment(isShowLevelChangeDialog:Boolean): XgPaResultFragment {
            mIsShowLevelChangeDialog = isShowLevelChangeDialog
            return XgPaResultFragment()
        }
    }

    private var scoreSoundUtil: ScoreSoundUtils? = null
    private lateinit var cognitiveBean: CognitiveBean
    private var isRefresh:Boolean = false

    override fun initView() {
        binding.IvBack.setOnClickListener {
            activity?.finish()
        }
        binding.IncludeA.LlScoreInforView.visibility = View.GONE
        binding.IncludeA.RlCenterView.visibility = View.GONE
        binding.IncludeB.LlResultParentView.visibility = View.GONE
        startSvgaLoading()
    }

    fun showResultView(){
        //初始化短音频
        scoreSoundUtil = ScoreSoundUtils(requireContext())
        scoreSoundUtil!!.init()
//        startSvgaLoading()
        binding.IncludeA.RlCenterView.visibility = View.GONE
        binding.IncludeA.LlScoreChangeView.visibility = View.GONE
        binding.IncludeA.DotProgressBar.visibility = View.VISIBLE
        binding.IncludeA.DotProgressBar.SetDotRadius(16f)
        binding.IncludeA.DotProgressBar.showNow()
        binding.IncludeA.LlScoreInforView.visibility = View.INVISIBLE//隐藏我的得分及作答时长水滴
        binding.IncludeB.LlResultParentView.visibility = View.INVISIBLE//隐藏答题卡标题
        binding.IncludeA.TvMyScore.setDinBoldTtf()
        binding.IncludeA.TvFullScore.setDinBoldTtf()
        binding.IncludeA.TvScoreChange1.setDinBoldTtf()
        binding.IncludeA.TvScoreChange2.setDinBoldTtf()

        cognitiveBean = ConstantBean.cognitiveBean!!
        binding.TvTitle.text = if (cognitiveBean.StuName.isNullOrEmpty()){
            "我的成绩"
        }else{
            "${cognitiveBean.StuName}的成绩"
        }
        //todo 模拟初始返回数据
        loadAndRefreshAnswerSheet()
    }


    private fun loadAndRefreshAnswerSheet() {
        //加载答题卡
        handler.sendEmptyMessage(0)
    }

    private lateinit var dialogLevelUp:XgDialogLevelUp
    private fun showLevelUpDialog(lastIndex: Int, currIndex: Int) {
        if(dialogLevelUp.isShowing){
            return
        }
        //webp动图
        dialogLevelUp = XgDialogLevelUp(requireActivity(), lastIndex, currIndex)
        dialogLevelUp.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        scoreSoundUtil?.stopAllSoundPool()
    }

    override fun onPause() {
        super.onPause()
        scoreSoundUtil?.stopAllSoundPool()
    }

    private fun translateAnimTop(view: View) {
        val translateAnimation = TranslateAnimation(
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_PARENT,
            1f,
            Animation.RELATIVE_TO_PARENT,
            0f
        )
        translateAnimation.duration = 800
        translateAnimation.fillAfter = true
        translateAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                view.visibility = View.VISIBLE
            }

            override fun onAnimationEnd(animation: Animation?) {
                showTopView()
            }

            override fun onAnimationRepeat(animation: Animation?) {

            }
        })
        view.startAnimation(translateAnimation)
    }

    private fun showTopView() {
        var score = cognitiveBean.Score
        score = DoubleUtils.killlingDouble(score!!.toDouble())
        var fullScore = cognitiveBean.FullScore
        fullScore = DoubleUtils.killlingDouble(fullScore!!.toDouble())
        val duration = cognitiveBean.Duration

        binding.IncludeA.TvPaperDuration.text = TimeUtils.secondToTimeEnglish(duration.toLong())
        binding.IncludeA.TvFullScore.text = fullScore
        if (binding.IncludeA.TvMyScore.text.toString() == "--") {
            //动态显示我的得分
            scoreSoundUtil!!.playSound(4)//添加数字累加音效
            if (score!!.contains(".")) {
                val length = score!!.substring(score!!.lastIndexOf(".") + 1).length
                if (length == 1) {
                    binding.IncludeA.TvMyScore.showNumberWithAnimation(
                        score!!.toFloat(),
                        CountNumberView.FLOATREGEX_1
                    )
                } else if (length == 2) {
                    binding.IncludeA.TvMyScore.showNumberWithAnimation(
                        score!!.toFloat(),
                        CountNumberView.FLOATREGEX_2
                    )
                }
            } else {
                binding.IncludeA.TvMyScore.showNumberWithAnimation(
                    score!!.toFloat(),
                    CountNumberView.INTREGEX
                )
            }
        } else {
            binding.IncludeA.TvMyScore.text = score
        }
    }

    private fun translateAnimCenter(view: View) {
        val translateAnimation = TranslateAnimation(
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_PARENT,
            1f,
            Animation.RELATIVE_TO_PARENT,
            0f
        )
        translateAnimation.duration = 600
        translateAnimation.fillAfter = true
        translateAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                view.visibility = View.VISIBLE
            }

            override fun onAnimationEnd(animation: Animation?) {
            }

            override fun onAnimationRepeat(animation: Animation?) {

            }
        })
        view.startAnimation(translateAnimation)
    }

    private fun translateAnimBottom(view: View) {
        val translateAnimation = TranslateAnimation(
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_SELF,
            0f,
            Animation.RELATIVE_TO_PARENT,
            1f,
            Animation.RELATIVE_TO_PARENT,
            0f
        )
        translateAnimation.duration = 1000
        translateAnimation.fillAfter = true
        translateAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                binding.IncludeB.LlResultParentView.visibility = View.VISIBLE
                stopSvgaLoading()
                //加载数据变化view
                handler.sendEmptyMessage(1)
            }

            override fun onAnimationEnd(animation: Animation?) {

            }

            override fun onAnimationRepeat(animation: Animation?) {

            }
        })
        view.startAnimation(translateAnimation)
    }

    private val handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> {
                    //加载答题卡
                    binding.IncludeB.RvResultParent.removeAllViews()
                    val adapterParent = XgPaResultAnswerSheetParentAdapter(
                        requireActivity(), cognitiveBean
                    )
                    adapterParent.setClickParentListener(object :
                        XgPaResultAnswerSheetParentAdapter.OnClickParentListener {
                        override fun onClick(index_A: Int, index_B: Int, index_C: Int) {
                            var sortIndex =
                                cognitiveBean.TypeList!![index_A].QuesList!![index_B].SortIndexList!![index_C].SortIndex
                            //跳转到已作答试题
                            EventBus.getDefault()
                                .post(ResultChildClickEvent(index_A, index_B, index_C))

                        }
                    })
                    binding.IncludeB.RvResultParent.adapter = adapterParent

                    Handler().postDelayed({
                        if (requireActivity().isFinishing) {
                            return@postDelayed
                        }
                        if(isRefresh){
                            sendEmptyMessage(1)
                        }else {
                            translateAnimBottom(binding.IncludeB.LlResultParentView)
                        }

                    }, 100)

                }
                1 -> {
                    if (cognitiveBean.CognitionInfo == null)
                        return

                    //加载成绩时间动画效果
                    if(isRefresh){
                        showTopView()
                    }else{
                        translateAnimTop(binding.IncludeA.LlScoreInforView)
                        translateAnimCenter(binding.IncludeA.RlCenterView)
                    }

                    //加载数值变化
                    showCognitiveAndScore()
                }
            }
        }
    }

    private var svgaUtils: SvgaUtils? = null
    private fun startSvgaLoading() {
        binding.SvgaLoading.visibility = View.VISIBLE
        svgaUtils = SvgaUtils(requireContext(), binding.SvgaLoading)
        svgaUtils!!.initAnimator()
        svgaUtils!!.startAnimator("小鸽加载");
    }

    private fun stopSvgaLoading() {
        svgaUtils!!.stopSVGA()
        binding.SvgaLoading.visibility = View.GONE
    }

    private fun showCognitiveAndScore() {
        val returnFlag = cognitiveBean.CognitionInfo!!.ReturnFlag
        if (returnFlag) {
            //显示认知分，预估成绩，得分，作答时长
            binding.IncludeA.DotProgressBar.visibility = View.GONE
            binding.IncludeA.DotProgressBar.hideNow()
            binding.IncludeA.LlScoreChangeView.visibility = View.VISIBLE

            val incrCognitiveIndex = cognitiveBean.CognitionInfo!!.IncrCognitiveIndex
            val incrEstimateScore = cognitiveBean.CognitionInfo!!.IncrEstimateScore
            binding.IncludeA.TvScoreTitle2.text = "${
                when (cognitiveBean.GlobalGrade) {
                    "K6", "K7", "K8", "K9" -> "中考"
                    else -> "高考"
                }
            }成绩"
            //动态显示我的认知分变化及预估成绩变化
            if (incrCognitiveIndex.contains("-")) {
                binding.IncludeA.TvScoreSymbols1.text = "↓"
                binding.IncludeA.TvScoreSymbols1.setTextColor(Color.parseColor("#f9c06e"))
                binding.IncludeA.TvScoreChange1.setTextColor(Color.parseColor("#f9c06e"))
                binding.IncludeA.TvUnit1.setTextColor(Color.parseColor("#f9c06e"))
            } else {
                binding.IncludeA.TvScoreSymbols1.text = "↑"
                binding.IncludeA.TvScoreSymbols1.setTextColor(Color.parseColor("#00e2bf"))
                binding.IncludeA.TvScoreChange1.setTextColor(Color.parseColor("#00e2bf"))
                binding.IncludeA.TvUnit1.setTextColor(Color.parseColor("#00e2bf"))
            }
            binding.IncludeA.TvScoreChange1.showNumberWithAnimation(
                abs(incrCognitiveIndex.toFloat()),
                CountNumberView.INTREGEX
            )


            if (incrEstimateScore.contains("-")) {
                binding.IncludeA.TvScoreSymbols2.text = "↓"
                binding.IncludeA.TvScoreSymbols2.setTextColor(Color.parseColor("#f9c06e"))
                binding.IncludeA.TvScoreChange2.setTextColor(Color.parseColor("#f9c06e"))
                binding.IncludeA.TvUnit2.setTextColor(Color.parseColor("#f9c06e"))
            } else {
                binding.IncludeA.TvScoreSymbols2.text = "↑"
                binding.IncludeA.TvScoreSymbols2.setTextColor(Color.parseColor("#00e2bf"))
                binding.IncludeA.TvScoreChange2.setTextColor(Color.parseColor("#00e2bf"))
                binding.IncludeA.TvUnit2.setTextColor(Color.parseColor("#00e2bf"))
            }
            binding.IncludeA.TvScoreChange2.showNumberWithAnimation(
                abs(incrEstimateScore.toFloat()),
                CountNumberView.INTREGEX
            )

            if(mIsShowLevelChangeDialog) {
                //判断是否显示升级、降级弹窗
                val lastCognitiveGrade = cognitiveBean.CognitionInfo!!.LastCognitiveGradeName
                val currCognitiveGrade = cognitiveBean.CognitionInfo!!.CurrCognitiveGradeName
                val lastIndex = LancooUtils.stringToAscii(lastCognitiveGrade).toInt()
                val currIndex = LancooUtils.stringToAscii(currCognitiveGrade).toInt()
                if (lastIndex != currIndex) {
                    Handler().postDelayed({
                        if (requireActivity().isFinishing) {
                            return@postDelayed
                        }

                        if (lastIndex != currIndex) {
                            if (lastIndex < currIndex) {
                                scoreSoundUtil!!.playSound(3)
                            } else if (lastIndex > currIndex) {
                                scoreSoundUtil!!.playSound(2)
                            }
                            showLevelUpDialog(lastIndex, currIndex)//成绩累加音频播放结束后显示弹窗
                        }
                    }, 2500)
                }
            }
        } else {
            binding.IncludeA.DotProgressBar.visibility = View.VISIBLE
            binding.IncludeA.LlScoreChangeView.visibility = View.GONE
        }
    }

    fun refreshResultScoreView(mCognitiveBean:CognitiveBean){
        isRefresh = true
        cognitiveBean = mCognitiveBean
        showCognitiveAndScore()
    }

    fun refreshResultAnswerSheetView(mCognitiveBean:CognitiveBean){
        isRefresh = true
        cognitiveBean = mCognitiveBean
        loadAndRefreshAnswerSheet()
    }

}